# Tesly automated test reporting
require 'config'
require 'test/unit/ui/console/testrunner'
require 'net/http'

# Info about custom headers: http://www.bigbold.com/snippets/posts/show/788

module Test
  module Unit
    module UI
      module Console
        class TestRunner
          alias_method :tesly_attach_to_mediator, :attach_to_mediator
                    
          def attach_to_mediator
            @mediator.add_listener(TestResult::FAULT, &method(:tesly_fault))
            @mediator.add_listener(TestRunnerMediator::STARTED, &method(:tesly_started))
            @mediator.add_listener(TestRunnerMediator::FINISHED, &method(:tesly_finished))
            @mediator.add_listener(TestCase::STARTED, &method(:tesly_test_started))
            @mediator.add_listener(TestCase::FINISHED, &method(:tesly_test_finished))
            tesly_attach_to_mediator
          end
          
          def tesly_fault(fault)
            @fault = true
          end
          
          def tesly_started(result)
            @tesly_results = {}
          end
          
          def tesly_finished(elapsed_time)
            # puts ""
            # puts "Requesting #{TeslyReporter::Config.host}/runner/#{TeslyReporter::Config.token}:"
            # puts ({ :failures => @failures, :successes => @successes }.to_yaml)
            begin
              Net::HTTP.post_form(URI.parse("#{TeslyReporter::Config.host}/runner/#{TeslyReporter::Config.token}"), {
                'results' => @tesly_results.to_yaml, 
                'project' => TeslyReporter::Config.app_name 
              })
            rescue
            end
          end
          
          def tesly_test_started(name)
            @fault = false
          end
          
          def tesly_test_finished(name)
            method, file = name.scan(/^([^\(]+)\(([^\)]+)\)/).flatten
            (@tesly_results[file] ||= []) << { :method => method, :fault => @fault }
          end
        end
      end
    end
  end
end